#!/usr/bin/bash
#
#  Usage: 保存容器镜像
#  Issue: 2024-05-14
# Author: Leon Hsia
#   Mail: waxwork3@163.com
#
if ! which realpath >/dev/null 2>&1; then
    echo "can't find command which is needed."
    exit 1
fi

base_path=$(dirname $(realpath $0))
cd $base_path

if [ ${#base_path} -le 4 ]; then
    echo "path too short."
    exit 1
fi

readarray -t images < <(grep 'image:' docker-compose.yml |awk '{print $2}')
while read line; do
    for image in "${images[@]}"; do
        image=$(echo $image |sed 's/^docker.io\///')
        id=$(echo "$line" |awk '{print $1":"$2" "$3}' |grep "^${image} " |awk '{print $2}')
        if [ "$id" != "" ]; then
            docker save -o $(echo "${image}.tar" |tr ':' '-' |tr '/' '-') "$image" "$id"
        fi
    done
done < <(docker images |grep -v REPOSITORY)